<template>
  <view class="container pd30">
    <!-- 头部 -->
    <!--uToast-->
    <u-toast ref="uToast" />
    <!---->

    <view class="contain">
      <view class="header">
        <view class="search">
          <view class="text">
            <!-- <image class="img" src="../../static/position.png"></image> -->
            <u-icon name="map" color="#fff" size="30" class="uicon"></u-icon>
            <view class="city">上海</view>
          </view>
          <view class="input" @click="toSearch">
            <u-search
              placeholder="大家都在搜索代理记账"
              v-model="searchWord"
              bg-color="#fff"
              clearabled
              :show-action="false"
            ></u-search>
          </view>
        </view>
        <view class="fixed_title" v-if="height > 40">
          <!-- <u-search
                      class="mt20"
                      placeholder="大家都在搜索代理记账"
                      v-model="searchWord"
                      bg-color="#f5f5f5"
                      clearabled
                      :show-action="false"
                    ></u-search> -->
          <search-bar @click.native="toSearch"></search-bar>
        </view>
        <view class="tab" style="width: 100%">
          <!-- <u-tabs
                      :list="list"
                      :is-scroll="false"
                      :current="current"
                      @change="change"

                      bg-color="#409EFF"
                     :bar-width="barWidth"
                      font-size="26"
                      bar-height="8"
                      inactive-color="#fff"
                      :active-item-style="activeStyle"
                      active-color="#fff"
                    ></u-tabs> -->
          <!-- <wuc-tab   :bar-width="barWidth" :tab-list="list" :tabCur.sync="current" tab-class="text-center bg-white wuc-tab" select-class="text-blue" @change="change"></wuc-tab> -->
        </view>
      </view>
      <view class="banner">
        <u-swiper
          @click="changeSwiperHandle"
          :list="bannerList"
          img-mode="scaleToFill"
          border-radius="16"
        ></u-swiper>
      </view>
    </view>
    <!-- <news v-if="current == 0 && articles.length > 0" :latestNews="articles" />
		<fiscalService v-if="current == 2" :currentType="selectedType" :currentArticle="articles" />
		<hrService v-if="current == 4" />
		<qualificationAgency v-if="current == 1"></qualificationAgency>
		<chooceServe v-if="current == 3"></chooceServe>
		<iegal v-if="current == 5"></iegal> -->
    <news
      :latestNews="articles"
      :longitude="longitude"
      :latitude="latitude"
      v-if="isShowCard"
    />
    <!-- <fiscalService  :currentType="selectedType" :currentArticle="articles" /> -->
    <!-- <hrService  /> -->
    <!-- <qualificationAgency></qualificationAgency> -->
    <!-- <chooceServe ></chooceServe> -->
    <!-- <iegal ></iegal> -->
    <!--法律-->
    <banner></banner>
    <!-- {{testaddress}} -->
    <!--底部轮播图-->
    <!--精选服务-->
    <recommend
      :themeTitle="themeTitle"
      :listQuery="selectedQuery"
      :pageLevel="pageLevel"
      @childFn="parentFn"
      :fromType="fromType"
    ></recommend>

    <divider></divider>
    <u-back-top :scroll-top="scrollTop"></u-back-top>

    <uni-popup ref="popup" type="center" class="popBox">
      <view class="popup_box">
        <view class="popClose">
          <u-icon
            name="close-circle"
            color="#f5f5f5"
            size="36"
            @click="closeHandle"
          ></u-icon>
        </view>
        <image
          class="coupImg"
          :src="activityCover"
          mode="aspectFit"
          style="width: 460rpx"
          @click.stop="ToActivity(popActivity)"
        ></image>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { mapState, mapMutations } from "vuex";

import SearchBar from "@/myComponents/searchBar";
import divider from "@/myComponents/divider/divider.vue";
import banner from "@/myComponents/banner/banner.vue";
import recommend from "@/myComponents/recommend/recommend.vue";
import news from "@/myComponents/index/news";
import hrService from "@/myComponents/index/hrService.vue";
import fiscalService from "@/myComponents/index/fiscalService.vue";
import chooceServe from "@/myComponents/chooceServe/index.vue";
import qualificationAgency from "@/myComponents/qualificationAgency/index.vue";
import iegal from "@/myComponents/index/iegal.vue";
import WucTab from "@/components/wuc-tab/wuc-tab.vue";
import uniPopup from "@/components/uni-popup/uni-popup.vue";
import io from "@/common/weapp.socket.io";

let socket;
export default {
  components: {
    news,
    banner,
    recommend,
    hrService,
    fiscalService,
    divider,
    chooceServe,
    qualificationAgency,
    iegal,
    SearchBar,
    uniPopup,
  },

  data() {
    return {
      closePupo: false,
      focusProp: false,
      activityCover:
        "https://eqiatong-public.oss-cn-beijing.aliyuncs.com/2021-01/06/0fcb66b8642348deb3cf20b251784464.png",
      activityIndex: 0,
      activityList: [],
      userInfo: {},
      socketData: {
        query: {
          room: "demo",
          userId: "",
        },
        transports: ["websocket", "polling"],
        timeout: 5000,
      },

      searchWhat: "search",
      height: "",
      list: [
        // {
        //   name: '法律服务',
        // },
      ],
      barWidth: 40,
      current: 0,
      searchWord: "",
      activeStyle: {
        "font-size": "14px",
      },
      barStyle: {
        // marginLeft:4+'rpx',
      },
      fromType: "1",
      bannerList: [
        // {
        //   image: "../../static/img/banner01.png",
        //   title: "公司注册",
        //   url: "../../pageTwo/financialService/register/register",
        //   type: "inside",
        // },
        // {
        //   image: "../../static/img/banner03.png",
        //   title: "资质代办",
        //   url: "../../pageTwo/financialService/keepAccount/keepAccount",
        //   type: "inside",
        // },
        // {
        //   image:
        //     "https://eqiatong-public.oss-cn-beijing.aliyuncs.com/2020-12/30/d2f5e62989b34509aeefa765aa6c6ce4.jpg",
        //   title: "元旦活动",
        //   url: "../../pages/activity/festival/festival",
        //   type: "inside",
        // },
      ],

      themeTitle: "精选服务",
      pageLevel: "one",
      selectedQuery: {
        Recommend: 1,
        currentPage: 1,
        pageSize: 7,
        status: 2,
        tree: false,
      },
      categoryQuery: {
        currentPage: 1,
        pageSize: 1,
        tree: true,
      },
      selectedType: {},
      articleQuery: {
        currentPage: 1,
        pageSize: 4,
        status: 0,
        tree: false,
      },
      bannerQuery: {
        currentPage: 1,
        pageSize: 5,
        status: "VALID",
        type: "HOME",
      },
      articles: [],
      status: "loadmore",
      reFresh: true,
      searchWhat: "serve",
      scrollTop: 0,
      testaddress: "",
      longitude: "",
      latitude: "",
      isShowCard: false,
      popActivity: {},
    };
  },
  onLoad() {
    //this.getCategory(); // 暂时注释
    this.latestArticle(); //最新轮播的文章

    this.getLocalCity(); // 获取本地位置  https有效
    this.getActivityList(); //获取活动

    this.getBannerList();

    if (
      uni.getStorageSync("userInfo") &&
      uni.getStorageSync("userInfo") != "null"
    ) {
      this.userInfo = JSON.parse(uni.getStorageSync("userInfo"));
      this.showCount(Number(this.userInfo.unReadCounts));
      // this.getActivityList();
     // this.socketData.query.userId = this.userInfo.id;
      socket = io(this.$IO, this.socketData);
      this.init();
    } 
    // else if 
    // (this.$route.query.token) {
    //   uni.setStorageSync("token", this.$route.query.token);
    //   this.getUserInfo(this.$route.query.token);
    // } else {
      
    // }
  },
  onShow() {
    if (
      uni.getStorageSync("userInfo") &&
      uni.getStorageSync("userInfo") != "null"
    ) {
      this.userInfo = JSON.parse(uni.getStorageSync("userInfo"));
      this.showCount(Number(this.userInfo.unReadCounts));
    } else {
      this.emptyCount();
    }
  },

  watch: {
    "$store.state.unReadCounts"(n, o) {
      this.showCount(Number(n));
    },
  },

  onReady() {
    this.open();
  },

  // 上拉加载
  onReachBottom() {
    if (this.reFresh) {
      this.selectedQuery.currentPage++;
    }
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.getFresh();
    this.getCategory();

    // 子组件能监听到
    (this.selectedQuery = {
      Recommend: 1,
      currentPage: 1,
      pageSize: 7,
      status: 2,
      tree: false,
      isrefresh: true,
    }),
      setTimeout(function () {
        uni.stopPullDownRefresh(); //停止下拉刷新动画
      }, 500);
  },

  methods: {
    getFresh() {
      this.reFresh = true;
    },
    //跳转到活动页
    ToActivity(value) {
      // 判断弹框

      var pathUrl = value.activityUrl

      if (value.inside) {
      
        uni.navigateTo({
          url: "../.."+pathUrl ,
        });
      } else {
        // #ifdef  H5
        window.location.href = pathUrl;
        // #endif

        // #ifdef  APP-PLUS
        plus.runtime.openURL(pathUrl);
        // #endif
      }
    },

    // Banner
    getBannerList() {
      this.$http
        .get("/api/banner/list", {
          params: this.bannerQuery,
        })
        .then((res) => {
          console.log(res.data.data);
          if (res.data.code == 20000) {
            var data = res.data.data;
            this.bannerList = data.records.length > 0 ? data.records : [];
          } else {
            uni.showToast({
              title: res.data.msg,
              icon: "none",
            });
          }
        });
    },
    init() {
      socket.on("connect", () => {
        console.log("ws 已连接");
        const { id } = socket;
        socket.on(id, (message) => {
          // 收到服务器推送的消息
          // $emit触发事件acceptMessage
          this.$eventHub.$emit("acceptMessage", message);
        });
      });
      socket.on("error", (msg) => {
        console.log("ws error", msg);
      });
    },
    ...mapMutations(["showCount", "emptyCount"]),

    getUserInfo: function getUserInfo(value) {
      let that = this;
      this.$http
        .get("/api/user/token", {
          header: {
            Authorization: value,
          },
        })
        .then(function (res) {
          // 存储到缓存
          uni.setStorageSync("userInfo", JSON.stringify(res.data.data));
          //存储用户id
          uni.setStorageSync("userId", res.data.data.id);

          that.userInfo = res.data.data;
          that.getActivityList();
        });
    },
    /**
     * 获取当前活动
     */
    // getActivityList() {
    //   this.$http
    //     .post("/api/jump", {
    //       url: "/api/activity/list",
    //       method: "get",
    //       parameter: {
    //         userId: this.userInfo ? this.userInfo.id : "",
    //       },
    //     })
    //     .then((res) => {
    //       //活动列表
    //       this.activityList = res.data.data || [];
    //       if (this.activityList.length > this.activityIndex) {
    //         // this.activityCover = this.activityList[
    //         //   this.activityIndex
    //         // ].activity_cover;
    //         this.$refs.popup.open();
    //       }
    //     });
    // },

    getActivityList() {
      this.$http.get("/api/activities/app").then((res) => {
        if (res.data.code == 20000) {
          var data = res.data.data;

          if (data) {
            this.popActivity = data;
            this.activityCover = data.popPic;
            this.$refs.popup.open();
          }
        } else {
        }
      });
    },

    getLocalCity() {
      var _this = this;
      uni.getLocation({
        type: "wgs84",
        success: function (res) {
          console.log("当前位置的经度：" + res.longitude);
          console.log("当前位置的纬度：" + res.latitude);
          this.longitude = res.longitude ? res.longitude : "121.4336";
          this.latitude = res.latitude ? this.latitude : "31.3390";

          var point = new plus.maps.Point(res.longitude, res.latitude);
          plus.maps.Map.reverseGeocode(
            point,
            {},
            function (event) {
              var address = event.address; // 转换后的地理位置
              var point = event.coord; // 转换后的坐标信息
              var coordType = event.coordType; // 转换后的坐标系类型
              console.log(address, "address");
              _this.testaddress = event;

              var reg = /.+?(省|市|自治区|自治州|县|区)/g;

              console.log(address.match(reg));
              _this.addressList = address.match(reg).toString().split(",");
              _this.address = _this.addressList[1];
            },
            function (e) {}
          );
        },
      });
    },

    async closeHandle() {
      this.$refs.popup.close();
      // if (this.userInfo ? this.userInfo.id : "") {
      //   let that = this;
      //   let data = this.activityList[this.activityIndex];
      //   if (data.activity_type === "COUPON") {
      //     //封装领劵动作
      //     let res = await that.$http.post("/api/jump", {
      //       url: "/api/coupon/users",
      //       method: "post",
      //       parameter: {
      //         userId: that.userInfo.id,
      //         couponId: data.activity_type_id,
      //       },
      //     });
      //     if (res.data.code === 20000) {
      //       that.$refs.uToast.show({
      //         title: "领取成功",
      //         type: "success",
      //         duration: 800,
      //         url: "/pageTwo/myCollect/myCoupon",
      //       });
      //       that.$refs.popup.close();
      //     }
      //   } else if (data.activity_type === "SERVICE") {
      //     that.$refs.popup.close();
      //     uni.navigateTo({
      //       url: `/pageTwo/productDetails/index?id=${data.activity_type_id}`,
      //     });
      //   }
      //   that.activityIndex += 1;
      //   if (that.activityList.length > that.activityIndex) {
      //     that.activityCover =
      //     that.activityList[that.activityIndex].activity_cover;
      //     that.$refs.popup.open();
      //   }
      // } else {
      //   uni.redirectTo({
      //     url: "../../pages/login/index",
      //   });
      // }
    },

    open() {},
    checkIsNew() {
      // // 判断是否是新户
      // if (uni.getStorageSync('userInfo')) {
      //     this.userInfo = JSON.parse(uni.getStorageSync('userInfo'))
      //     console.log( this.userInfo)
      //     var isNewUser =  this.userInfo.isNewUser
      //     this.$refs.popup.open()
      //     // if(isNewUser){
      //     //      this.$refs.popup.open()
      //     // }else{
      //     //     this.$refs.popup.close()
      //     // }
      // }
    },
    toSearch() {
      uni.navigateTo({
        url:
          `../../pageTwo/searchBarPage/index?searchWhat=${this.searchWhat}` +
          "&fromType=" +
          1,
      });
    },
    parentFn(paylaod) {
      //停止刷新
      this.reFresh = false;
    },

    getCategory() {
      this.$http
        .get("/api/server/list", {
          params: this.categoryQuery,
        })
        .then((res) => {
          var data = res.data.data.categorys;
          // 替换对象的key

          if (data) {
            var newList = data.map((item, index) => {
              return {
                name: item.label,
                id: item.id,
              };
            });
            this.list = [];
            newList.unshift({
              name: "首页",
            });
            // 目前写死 后面后台配置 该模块
            // newList.push({ name: "法律服务" });
            // this.list = this.list.concat(test)
            this.list = newList;

            console.log(this.list);

            uni.hideNavigationBarLoading();
          }
        });
    },

    latestArticle() {
      this.$http
        .get("/api/article/list", {
          params: this.articleQuery,
        })
        .then((res) => {
          this.isShowCard = true;
          if (res.data.code == 20000) {
            this.articles = res.data.data.articles;
          } else {
            uni.showToast({
              title: res.data.msg,
              icon: "none",
            });
          }
        });
    },
    changeSwiperHandle(e) {
      var pathUrl = this.bannerList[e].url;

      if (this.bannerList[e].inside) {
        uni.navigateTo({
          url: "../.." + pathUrl,
        });
      } else {
        // #ifdef  H5
        window.location.href = pathUrl;
        // #endif

        // #ifdef  APP-PLUS
        plus.runtime.openURL(pathUrl);
        // #endif
      }
    },

    change(index) {
      this.current = index;
      this.selectedType = this.list[index];
    },
    get(i) {
      this.current = i;
    },
  },
  onPageScroll(e) {
    this.height = this.scrollTop = e.scrollTop;
  },
  created() {
    //接收事件
    this.$eventHub.$on("sendMessage", function (data) {
      socket.emit("exchange", data); // 发送给服务器
    });
  },
};
</script>

<style lang="scss" scoped>
.container {
  font-size: 28rpx;

  .contain {
    position: relative;

    // margin-bottom: 200rpx;
    .header {
      background: #409eff;
      height: 300rpx;
      padding-top: 66rpx;

      .search {
        height: 88rpx;
        padding: 0 30rpx;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        color: #fff;
        .text {
          display: flex;
        }

        // .text {
        // 	height: 88rpx;
        // 	width: 100rpx;
        // 	padding-top: 24rpx;
        // 	box-sizing: border-box;
        // 	position: relative;
        // 	padding-left: 10rpx;

        // 	.uicon {
        // 		float: left;
        // 		margin-top: 4rpx;
        // 	}

        // 	.img {
        // 		position: absolute;
        // 		top: 0;
        // 		left: 0;
        // 		margin-top: 30rpx;
        // 		display: inline-block;
        // 		width: 32rpx;
        // 		height: 32rpx;
        // 	}
        // }

        .input {
          flex: 1;
          padding-left: 14rpx;
        }
      }
    }

    .banner {
      position: absolute;
      width: 690rpx;
      height: 236rpx;
      left: 30rpx;
      top: 180rpx;
    }
  }

  .popClose {
    display: flex;
    justify-content: flex-end;
    // position: relative;
    // background: #409eff;
    // top: 10px;
  }
}

.grid-text {
  font-size: 26rpx;
  margin-top: 20rpx;
  color: #333333;
}

.mt {
  margin-top: 200rpx;
}

.bg-white {
  background-color: #409eff;
}

.text-center {
  text-align: center;
}

.fixed_title {
  width: 90%;
  margin: 0 auto;
  height: 100rpx;
  line-height: 100rpx;
  background-color: #fff;
  position: fixed;
  top: 0rpx;
  z-index: 100;
  // padding: 0 30rpx;
}


</style>
